package com.atguigu.flink.watermark;

import com.atguigu.flink.function.WaterSensorMapFunction;
import com.atguigu.flink.pojo.WaterSensor;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.TimerService;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;

/**
 * Created by Smexy on 2022/12/16
 *
 *  默认水印时周期性(200ms)产生,当没有数据时，会向流中发送 -Long.max
 */
public class Demo2_GetWaterMark
{
    public static void main(String[] args) {

       Configuration conf = new Configuration();
       conf.setInteger("rest.port", 3333);
       StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);

       //设置水印的发送间隔  2000ms
        env.getConfig().setAutoWatermarkInterval(2000);

        env.setParallelism(1);

        WatermarkStrategy<WaterSensor> watermarkStrategy = WatermarkStrategy.<WaterSensor>forMonotonousTimestamps()
            .withTimestampAssigner( (e, r) -> e.getTs());

        env
                   .socketTextStream("hadoop103", 8888)
                   .map(new WaterSensorMapFunction())
                   .assignTimestampsAndWatermarks(watermarkStrategy)
                   .process(new ProcessFunction<WaterSensor, WaterSensor>()
                   {
                       @Override
                       public void processElement(WaterSensor value, Context ctx, Collector<WaterSensor> out) throws Exception {

                           //时间服务  1.获取水印  2.注册定时器
                           TimerService timerService = ctx.timerService();

                           // currentWatermark: 数据达到时，算子的当前时钟
                           System.out.println("当前数据达到时，这个算子的水印(时钟)"+timerService.currentWatermark());
                           System.out.println("当前数据达到时，这个算子的物理时钟"+timerService.currentProcessingTime());
                           out.collect(value);
                       }
                   }).startNewChain()
                   .print();


                try {
                            env.execute();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

    }
}
